<template>
  <div class="system-monitor">
    <el-row :gutter="20">
      <!-- 系统资源监控 -->
      <el-col :xs="24" :lg="12">
        <el-card title="系统资源监控">
          <template #header>
            <span>系统资源监控</span>
            <el-button type="text" @click="refreshData">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </template>
          
          <div class="resource-item">
            <div class="resource-label">CPU使用率</div>
            <el-progress :percentage="systemInfo.cpu" :color="getProgressColor(systemInfo.cpu)" />
            <div class="resource-value">{{ systemInfo.cpu }}%</div>
          </div>
          
          <div class="resource-item">
            <div class="resource-label">内存使用率</div>
            <el-progress :percentage="systemInfo.memory" :color="getProgressColor(systemInfo.memory)" />
            <div class="resource-value">{{ systemInfo.memory }}%</div>
          </div>
          
          <div class="resource-item">
            <div class="resource-label">磁盘使用率</div>
            <el-progress :percentage="systemInfo.disk" :color="getProgressColor(systemInfo.disk)" />
            <div class="resource-value">{{ systemInfo.disk }}%</div>
          </div>
          
          <div class="resource-item">
            <div class="resource-label">网络IO</div>
            <div class="network-info">
              <span>上传: {{ systemInfo.networkUp }} MB/s</span>
              <span>下载: {{ systemInfo.networkDown }} MB/s</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 服务状态监控 -->
      <el-col :xs="24" :lg="12">
        <el-card title="服务状态监控">
          <template #header>
            <span>服务状态监控</span>
          </template>
          
          <div class="service-list">
            <div
              v-for="service in serviceList"
              :key="service.name"
              class="service-item"
            >
              <div class="service-info">
                <div class="service-name">{{ service.name }}</div>
                <div class="service-desc">{{ service.description }}</div>
              </div>
              <div class="service-status">
                <el-tag :type="service.status === 'running' ? 'success' : 'danger'">
                  {{ service.status === 'running' ? '运行中' : '已停止' }}
                </el-tag>
                <el-button
                  :type="service.status === 'running' ? 'warning' : 'success'"
                  size="small"
                  @click="toggleService(service)"
                >
                  {{ service.status === 'running' ? '停止' : '启动' }}
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 实时日志 -->
      <el-col :span="24">
        <el-card title="实时日志">
          <template #header>
            <div class="log-header">
              <span>实时日志</span>
              <div>
                <el-button type="text" @click="clearLogs">清空日志</el-button>
                <el-button type="text" @click="toggleAutoRefresh">
                  {{ autoRefresh ? '停止自动刷新' : '开始自动刷新' }}
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="log-container" ref="logContainer">
            <div
              v-for="log in logList"
              :key="log.id"
              :class="['log-item', `log-${log.level}`]"
            >
              <span class="log-time">{{ log.time }}</span>
              <span class="log-level">{{ log.level.toUpperCase() }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

// 响应式数据
const autoRefresh = ref(false)
const refreshTimer = ref<NodeJS.Timeout | null>(null)
const logContainer = ref<HTMLElement>()

// 系统信息
const systemInfo = reactive({
  cpu: 45,
  memory: 68,
  disk: 32,
  networkUp: 2.5,
  networkDown: 8.3
})

// 服务列表
const serviceList = ref([
  {
    name: 'nginx',
    description: 'Web服务器',
    status: 'running'
  },
  {
    name: 'mysql',
    description: '数据库服务',
    status: 'running'
  },
  {
    name: 'redis',
    description: '缓存服务',
    status: 'running'
  },
  {
    name: 'docker',
    description: '容器服务',
    status: 'stopped'
  }
])

// 日志列表
const logList = ref([
  {
    id: 1,
    time: '2024-01-15 14:30:25',
    level: 'info',
    message: '系统启动完成'
  },
  {
    id: 2,
    time: '2024-01-15 14:30:26',
    level: 'warning',
    message: 'CPU使用率较高，当前45%'
  },
  {
    id: 3,
    time: '2024-01-15 14:30:27',
    level: 'error',
    message: 'Docker服务未启动'
  }
])

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 50) return '#67C23A'
  if (percentage < 80) return '#E6A23C'
  return '#F56C6C'
}

// 刷新数据
const refreshData = () => {
  // 模拟数据更新
  systemInfo.cpu = Math.floor(Math.random() * 100)
  systemInfo.memory = Math.floor(Math.random() * 100)
  systemInfo.disk = Math.floor(Math.random() * 100)
  systemInfo.networkUp = Math.random() * 10
  systemInfo.networkDown = Math.random() * 20
  
  ElMessage.success('数据刷新成功')
}

// 切换服务状态
const toggleService = (service: any) => {
  service.status = service.status === 'running' ? 'stopped' : 'running'
  
  const action = service.status === 'running' ? '启动' : '停止'
  ElMessage.success(`${service.name} 服务${action}成功`)
  
  // 添加日志
  addLog('info', `${service.name} 服务已${action}`)
}

// 添加日志
const addLog = (level: string, message: string) => {
  const newLog = {
    id: Date.now(),
    time: new Date().toLocaleString(),
    level,
    message
  }
  
  logList.value.unshift(newLog)
  
  // 限制日志数量
  if (logList.value.length > 100) {
    logList.value = logList.value.slice(0, 100)
  }
  
  // 滚动到顶部
  nextTick(() => {
    if (logContainer.value) {
      logContainer.value.scrollTop = 0
    }
  })
}

// 清空日志
const clearLogs = () => {
  logList.value = []
  ElMessage.success('日志已清空')
}

// 切换自动刷新
const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value
  
  if (autoRefresh.value) {
    refreshTimer.value = setInterval(() => {
      refreshData()
      // 模拟添加新日志
      const levels = ['info', 'warning', 'error']
      const messages = [
        '系统运行正常',
        'CPU使用率波动',
        '内存使用率上升',
        '网络连接正常',
        '磁盘空间充足'
      ]
      
      const randomLevel = levels[Math.floor(Math.random() * levels.length)]
      const randomMessage = messages[Math.floor(Math.random() * messages.length)]
      
      addLog(randomLevel, randomMessage)
    }, 5000)
    
    ElMessage.success('已开启自动刷新')
  } else {
    if (refreshTimer.value) {
      clearInterval(refreshTimer.value)
      refreshTimer.value = null
    }
    ElMessage.info('已停止自动刷新')
  }
}

// 组件挂载
onMounted(() => {
  refreshData()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
  }
})
</script>

<style scoped>
.system-monitor {
  padding: 20px;
}

.resource-item {
  margin-bottom: 20px;
}

.resource-item:last-child {
  margin-bottom: 0;
}

.resource-label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.resource-value {
  margin-top: 8px;
  text-align: right;
  font-weight: bold;
  color: #666;
}

.network-info {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.service-list {
  max-height: 400px;
  overflow-y: auto;
}

.service-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
}

.service-item:last-child {
  border-bottom: none;
}

.service-info {
  flex: 1;
}

.service-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.service-desc {
  font-size: 12px;
  color: #666;
}

.service-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-container {
  height: 300px;
  overflow-y: auto;
  background-color: #1e1e1e;
  padding: 10px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
}

.log-item {
  margin-bottom: 5px;
  font-size: 12px;
  line-height: 1.4;
}

.log-time {
  color: #888;
  margin-right: 10px;
}

.log-level {
  margin-right: 10px;
  font-weight: bold;
}

.log-info .log-level {
  color: #67C23A;
}

.log-warning .log-level {
  color: #E6A23C;
}

.log-error .log-level {
  color: #F56C6C;
}

.log-message {
  color: #fff;
}
</style>
